<template>
  <view class="register-page">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="bg-circle bg-circle-1"></view>
      <view class="bg-circle bg-circle-2"></view>
      <view class="bg-circle bg-circle-3"></view>
    </view>
    
    <!-- 自定义导航栏 -->
    <u-navbar 
      :is-back="true" 
      title="注册" 
      title-color="#fff"
      bg-color="rgba(255,255,255,0.9)"
      :border-bottom="false"
    />
    
    <!-- 页面内容 -->
    <view class="register-container">
      <!-- Logo区域 -->
      <view class="logo-section">
        <image class="logo" src="/static/logo.png" mode="aspectFit" />
        <text class="app-name">每日记</text>
        <text class="app-slogan">开始记录你的美好时光</text>
      </view>
      
      <!-- 注册表单 -->
      <view class="register-form">
        <!-- 用户名输入 -->
        <view class="input-group">
          <view class="input-label">
            <text>用户名</text>
          </view>
          <view class="input-wrapper">
            <input
              v-model="formData.username"
              placeholder="请输入用户名"
              class="input-field"
              placeholder-class="input-placeholder"
            />
          </view>
        </view>
        
        <!-- 邮箱输入 -->
        <view class="input-group">
          <view class="input-label">
            <text>邮箱</text>
          </view>
          <view class="input-wrapper">
            <input
              v-model="formData.email"
              placeholder="请输入邮箱地址"
              type="email"
              class="input-field"
              placeholder-class="input-placeholder"
            />
          </view>
        </view>
        
        <!-- 昵称输入 -->
        <view class="input-group">
          <view class="input-label">
            <text>昵称（可选）</text>
          </view>
          <view class="input-wrapper">
            <input
              v-model="formData.nickname"
              placeholder="请输入昵称"
              class="input-field"
              placeholder-class="input-placeholder"
            />
          </view>
        </view>
        
        <!-- 密码输入 -->
        <view class="input-group">
          <view class="input-label">
            <text>密码</text>
          </view>
          <view class="input-wrapper">
            <input
              v-model="formData.password"
              placeholder="请输入密码"
              :password="!showPassword"
              class="input-field"
              placeholder-class="input-placeholder"
            />
            <view class="password-toggle" @click="togglePassword">
              <text>{{ showPassword ? '隐藏' : '显示' }}</text>
            </view>
          </view>
        </view>
        
        <!-- 确认密码输入 -->
        <view class="input-group">
          <view class="input-label">
            <text>确认密码</text>
          </view>
          <view class="input-wrapper">
            <input
              v-model="formData.confirmPassword"
              placeholder="请再次输入密码"
              :password="!showConfirmPassword"
              class="input-field"
              placeholder-class="input-placeholder"
            />
            <view class="password-toggle" @click="toggleConfirmPassword">
              <text>{{ showConfirmPassword ? '隐藏' : '显示' }}</text>
            </view>
          </view>
        </view>
        
        <!-- 密码强度提示 -->
        <view class="password-strength" v-if="formData.password">
          <view class="strength-bar">
            <view 
              class="strength-item" 
              :class="getStrengthClass(0)"
            ></view>
            <view 
              class="strength-item" 
              :class="getStrengthClass(1)"
            ></view>
            <view 
              class="strength-item" 
              :class="getStrengthClass(2)"
            ></view>
          </view>
          <text class="strength-text" :class="strengthClass">{{ strengthText }}</text>
        </view>
        
        <!-- 用户协议 -->
        <view class="agreement">
          <view class="agreement-item" @click="toggleAgreement">
            <view class="checkbox" :class="{ checked: agreed }">
              <text v-if="agreed" class="checkbox-mark">✓</text>
            </view>
            <text class="agreement-text">
              我已阅读并同意
              <text class="agreement-link" @click.stop="viewAgreement('user')">《用户协议》</text>
              和
              <text class="agreement-link" @click.stop="viewAgreement('privacy')">《隐私政策》</text>
            </text>
          </view>
        </view>
        
        <!-- 注册按钮 -->
        <view class="register-button-wrapper">
          <button 
            class="register-btn"
            :class="{ disabled: !canRegister }"
            :disabled="!canRegister || loading"
            @click="handleRegister"
          >
            <text v-if="loading">注册中...</text>
            <text v-else>注册</text>
          </button>
        </view>
        
        <!-- 登录链接 -->
        <view class="login-link">
          <text class="link-text">已有账号？</text>
          <text class="link-btn" @click="goToLogin">立即登录</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/store/user'
import { registerAPI } from '@/api/auth'
import { isValidEmail, isValidPhone } from '@/utils/index'

export default {
  name: 'RegisterPage',
  setup() {
    const userStore = useUserStore()
    return {
      userStore
    }
  },
  data() {
    return {
      formData: {
        username: '',
        email: '',
        nickname: '',
        password: '',
        confirmPassword: ''
      },
      showPassword: false,
      showConfirmPassword: false,
      agreed: false,
      loading: false
    }
  },
  computed: {
    canRegister() {
      return this.formData.username.trim() && 
             this.formData.email.trim() &&
             this.formData.password.trim() &&
             this.formData.confirmPassword.trim() &&
             this.agreed
    },
    
    passwordStrength() {
      const password = this.formData.password
      if (!password) return 0
      
      let strength = 0
      // 长度检查
      if (password.length >= 6) strength++
      // 包含数字和字母
      if (/(?=.*[0-9])(?=.*[a-zA-Z])/.test(password)) strength++
      // 包含特殊字符
      if (/[^a-zA-Z0-9]/.test(password)) strength++
      
      return strength
    },
    
    strengthText() {
      switch (this.passwordStrength) {
        case 1: return '弱'
        case 2: return '中'
        case 3: return '强'
        default: return ''
      }
    },
    
    strengthClass() {
      switch (this.passwordStrength) {
        case 1: return 'weak'
        case 2: return 'medium'
        case 3: return 'strong'
        default: return ''
      }
    }
  },
  onLoad() {
    this.initPage()
  },
  methods: {
    initPage() {
      // 检查是否已登录
      if (this.userStore.isLogin) {
        uni.switchTab({
          url: '/pages/index/index'
        })
        return
      }
    },
    
    togglePassword() {
      this.showPassword = !this.showPassword
    },
    
    toggleConfirmPassword() {
      this.showConfirmPassword = !this.showConfirmPassword
    },
    
    toggleAgreement() {
      this.agreed = !this.agreed
    },
    
    getStrengthClass(index) {
      const strength = this.passwordStrength
      const classes = ['weak', 'medium', 'strong']
      
      if (index < strength) {
        return classes[strength - 1]
      }
      return ''
    },
    
    async handleRegister() {
      if (!this.validateForm()) return
      
      this.loading = true
      try {
        const registerData = {
          username: this.formData.username.trim(),
          email: this.formData.email.trim(),
          nickname: this.formData.nickname.trim(),
          password: this.formData.password.trim()
        }
        
        const res = await registerAPI(registerData)
        
        // 注册成功判断 - 服务器返回数据包含message和token即为成功
        if (res.message && res.token) {
          // 注册成功
          uni.showToast({
            title: '注册成功，请登录',
            icon: 'success'
          })
          
          // 延迟跳转到登录页
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/login/login'
            })
          }, 1500)
        } else {
          // 注册失败
          uni.showToast({
            title: res.message || '注册失败，请重试',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('注册失败:', error)
        uni.showToast({
          title: error.message || '注册失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    validateForm() {
      // 用户名验证
      if (!this.formData.username.trim()) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        })
        return false
      }
      
      if (this.formData.username.length < 3 || this.formData.username.length > 30) {
        uni.showToast({
          title: '用户名长度在3到30个字符',
          icon: 'none'
        })
        return false
      }
      
      // 用户名只能包含字母和数字
      if (!/^[a-zA-Z0-9]+$/.test(this.formData.username)) {
        uni.showToast({
          title: '用户名只能包含字母和数字',
          icon: 'none'
        })
        return false
      }
      
      // 邮箱验证
      if (!this.formData.email.trim()) {
        uni.showToast({
          title: '请输入邮箱地址',
          icon: 'none'
        })
        return false
      }
      
      if (!isValidEmail(this.formData.email)) {
        uni.showToast({
          title: '请输入正确的邮箱地址',
          icon: 'none'
        })
        return false
      }
      
      // 昵称验证（可选）
      if (this.formData.nickname.trim() && this.formData.nickname.length > 50) {
        uni.showToast({
          title: '昵称不能超过50个字符',
          icon: 'none'
        })
        return false
      }
      
      // 密码验证
      if (!this.formData.password.trim()) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return false
      }
      
      if (this.formData.password.length < 6 || this.formData.password.length > 128) {
        uni.showToast({
          title: '密码长度在6到128个字符',
          icon: 'none'
        })
        return false
      }
      
      // 确认密码验证
      if (!this.formData.confirmPassword.trim()) {
        uni.showToast({
          title: '请确认密码',
          icon: 'none'
        })
        return false
      }
      
      if (this.formData.password !== this.formData.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        })
        return false
      }
      
      // 协议验证
      if (!this.agreed) {
        uni.showToast({
          title: '请先同意用户协议和隐私政策',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    viewAgreement(type) {
      const urls = {
        user: '/pages/agreement/user',
        privacy: '/pages/agreement/privacy'
      }
      
      uni.navigateTo({
        url: urls[type] || '/pages/agreement/user'
      })
    },
    
    goToLogin() {
      uni.redirectTo({
        url: '/pages/login/login'
      })
    }
  }
}
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  position: relative;
  overflow: hidden;
}

.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.bg-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.bg-circle-1 {
  width: 200rpx;
  height: 200rpx;
  top: 15%;
  right: -60rpx;
  animation-delay: 0s;
}

.bg-circle-2 {
  width: 150rpx;
  height: 150rpx;
  top: 70%;
  left: -50rpx;
  animation-delay: 2s;
}

.bg-circle-3 {
  width: 100rpx;
  height: 100rpx;
  top: 45%;
  right: 10%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-15px);
  }
}

.register-container {
  position: relative;
  z-index: 1;
  padding: 40rpx 60rpx;
  min-height: calc(100vh - 88rpx);
}

.logo-section {
  text-align: center;
  margin: 60rpx 0 80rpx;
}

.logo {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 24rpx;
}

.app-name {
  display: block;
  font-size: 44rpx;
  font-weight: bold;
  color: #ffffff;
  margin: 28rpx 0 12rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.app-slogan {
  display: block;
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.8);
}

.register-form {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 32rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.input-group {
  margin-bottom: 32rpx;
}

.input-label {
  margin-bottom: 16rpx;
}

.input-label text {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border: 2rpx solid #e5e5e5;
  border-radius: 16rpx;
  padding: 0 24rpx;
  min-height: 88rpx;
  transition: all 0.3s;
}

.input-wrapper:focus-within {
  border-color: #1890ff;
  box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.1);
}

.input-field {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  background-color: transparent;
  border: none;
  outline: none;
  height: 100%;
}

.input-placeholder {
  color: #999999;
}

.password-toggle {
  padding: 8rpx 16rpx;
  color: #1890ff;
  font-size: 24rpx;
}

.password-strength {
  margin-top: 16rpx;
  margin-bottom: 24rpx;
}

.strength-bar {
  display: flex;
  gap: 8rpx;
  margin-bottom: 8rpx;
}

.strength-item {
  flex: 1;
  height: 6rpx;
  background-color: #e5e5e5;
  border-radius: 3rpx;
  transition: all 0.3s;
}

.strength-item.weak {
  background-color: #ff4d4f;
}

.strength-item.medium {
  background-color: #faad14;
}

.strength-item.strong {
  background-color: #52c41a;
}

.strength-text {
  font-size: 24rpx;
}

.strength-text.weak {
  color: #ff4d4f;
}

.strength-text.medium {
  color: #faad14;
}

.strength-text.strong {
  color: #52c41a;
}

.agreement {
  margin: 32rpx 0 40rpx;
}

.agreement-item {
  display: flex;
  align-items: flex-start;
}

.checkbox {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #d9d9d9;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  margin-top: 4rpx;
  flex-shrink: 0;
}

.checkbox.checked {
  background-color: #1890ff;
  border-color: #1890ff;
}

.checkbox-mark {
  color: #ffffff;
  font-size: 20rpx;
  font-weight: bold;
}

.agreement-text {
  font-size: 24rpx;
  color: #666666;
  line-height: 1.5;
  margin-left: 16rpx;
}

.agreement-link {
  color: #1890ff;
  text-decoration: underline;
}

.register-button-wrapper {
  margin: 40rpx 0;
}

.register-btn {
  width: 100%;
  height: 88rpx;
  background-color: #1890ff;
  color: #ffffff;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.register-btn.disabled {
  background-color: #d9d9d9;
  color: #ffffff;
}

.register-btn::after {
  border: none;
}

.login-link {
  text-align: center;
  margin-top: 32rpx;
}

.link-text {
  font-size: 28rpx;
  color: #666666;
  margin-right: 16rpx;
}

.link-btn {
  font-size: 28rpx;
  color: #1890ff;
}

/* 深色主题适配 */
@media (prefers-color-scheme: dark) {
  .register-page {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  }
  
  .app-name {
    color: #ffffff;
  }
  
  .app-slogan {
    color: rgba(255, 255, 255, 0.7);
  }
}
</style> 